/* eslint-disable no-unused-vars */
/* eslint-disable prefer-const */
/*
 * @Author: shawnxiao
 * @Date: 2021-04-27 18:30:44
 * @LastEditTime: 2021-05-11 16:46:56
 * @FilePath: /project/src/components/UploadCom/index.tsx
 */
import { createElement } from 'react'
import { Upload, message } from 'antd'
const h = createElement
const SUFFIX = /.+(\.\w+)$/,
      BYTE = 1024,
      ACCEPT = {
        zip: 'application/zip,application/x-zip,application/x-zip-compressed',
        pdf: 'application/pdf',
        excel: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        image: 'image/jpeg,image/bmp,image/png,image/gif',
        word: 'application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        ppt: 'application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation'
      },
      getAccepts = (accept:any) => (Array.isArray(accept) ? accept : [accept]).map(ac => ACCEPT[ac]).join(','),
      beforeCheck = (config:any, file:any):any => {
        // let { accept, max = Number.MAX_VALUE } = config || {}, { size, type } = file, accepts = getAccepts(accept).split(',')
        let { max = Number.MAX_VALUE } = config || {}, { size } = file
        // 大小限制(M)
        if (Math.pow(BYTE, 2) * max < size){
          message.info(`文件不能超过${max}M`)
          return false
        }
      }

  const UploadCom = (props:any) => {
    let { children, config } = props, { accept } = config, attrs = {}
    // 不能在props对象上直接添加属性，只能再定义一个attrs对象
    Object.assign(attrs, {
      action: '',
      accept: getAccepts(accept),
      beforeUpload: (file:any) => beforeCheck(config, file),
      customRequest: (opts:any) => {
        let { file, onSuccess }:any = opts, { uid, name, type } = file, regExp = /image\/[a-z]{2,4}$/i
        name = `${uid}${name.replace(SUFFIX, '$1')}`
        // 判断上传的文件是否是图片，若不是图片，前端可自行根据isImg来控制是否可预览文件
        file.isImg = regExp.test(type) ? true : false
        // fetch('https://jsonplaceholder.typicode.com/posts', {
        //   method: 'POST',
        //   body: file,
        // }).then(r => {
        //   let { res: { requestUrls } } = r;
        //   requestUrls = requestUrls.length < 1 ? '' : requestUrls[0]
        //   if (requestUrls.indexOf('?') > -1) requestUrls = requestUrls.split('?')[0]
        //   onSuccess({ res: file, url: requestUrls });
        // })
        const resFile = {
          uid,
          name,
          url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
        }
        onSuccess(resFile)
      }
    })
    return h(Upload, {...props, ...attrs}, children)
  }

  export default UploadCom
